package mysql;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import enumeration.RobStrategy;
import user.User;

import java.sql.*;
import java.util.*;

public class MysqlUtil {

    // MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/robClass?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false";

    // MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
    //static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    //static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";

    final static String username = "root";
    final static String password = "root";
    private static Connection connection;
    private static Statement statement;

    public static void initMysql() {
        try {
            Class.forName(JDBC_DRIVER);
            System.out.println("connect to mysql...");
            connection = DriverManager.getConnection(DB_URL, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    public static ResultSet select(String sql) {
        if (connection == null) {
            initMysql();
            return select(sql);
        }
        try {
            System.out.println(sql);
            statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            return resultSet;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    /*
    * username int(50) #每秒
     password int(50)
     startTime Date #开始时间
     thread int(5) 每秒线程
     strategy int 抢课策略  ->enum  0 List 1 Random 2 All
     state int  抢课是否成功 0 未成功 1 成功
      */
    public static ResultSet selectUsers() {
        String selectSql = "select * from user";
        ResultSet resultSet = select(selectSql);
        return resultSet;
    }

    public static ResultSet selectUser(User user) {
        String selectSql = "select * from user where username= " + user.getUsername();
        ResultSet resultSet = select(selectSql);
        try {
            if (resultSet.next()) {
                return resultSet;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static ResultSet updateUser(User user) {

        if (connection == null) {
            initMysql();
        }
        //先查询是否存在 再插入
        //如果存在就更新

        String insertSql = "insert into user values(?,?,?,?,?,?,?,?,?)";

        String updateSql = "update user SET username= ?, password=?,studentName=?, startTime=?, thread=?,strategy=?,robClasses=?,robCommonClasses=?,robEnable=? where username = " + user.getUsername();
        PreparedStatement preparedStatement;
        try {
            if (selectUser(user) != null) { //update state
                preparedStatement = connection.prepareStatement(updateSql);
            } else {
                preparedStatement = connection.prepareStatement(insertSql);
            }
            preparedStatement.setString(1, user.getUsername());
            preparedStatement.setString(2, user.getPassword());
            preparedStatement.setString(3, user.getStudentName());
            preparedStatement.setString(4, user.getStartTime());
            preparedStatement.setInt(5, user.getThreads());
            preparedStatement.setInt(6, user.getRobStrategy().ordinal());
            preparedStatement.setString(7, JSON.toJSONString(user.getRobClasses(), SerializerFeature.WriteClassName));
            preparedStatement.setString(8, JSON.toJSONString(user.getRobCommonClasses(), SerializerFeature.WriteClassName));
            preparedStatement.setInt(9, user.getRobEnable());
            int rs = preparedStatement.executeUpdate();
            System.out.println("改动了" + rs + "行");

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取用户
     * 1.缓存获取
     * 2.数据库获取
     */
    public static User getUser(User user) {
        Scanner strInput = new Scanner(System.in, "UTF-8");

        if (user == null) {
            System.out.println("=========================================登陆操作=========================================");
            System.out.println("正方账号:");
            String input = null;
            if (strInput.hasNext()) {
                input = strInput.next();
                user = User.userCache.get(input);
                if (user != null) {
                    return user;
                }
            }
            user = new User();
            user.setUsername(input);
            ResultSet rs = MysqlUtil.selectUser(user);
            if (rs != null) {
                user = initUser(rs);
            } else {
                System.out.println("获取不到用户信息! 目前判断你是新用户! 请去填写个人资料!");
                return null;
            }

        }


        User.userCache.put(user.getUsername(), user);
        System.out.println("获取用户信息成功!");
//        System.out.println(user);
        return user;
    }

    public static ArrayList<User> getUsers(User user) {
        ArrayList<User> users = new ArrayList<>();
        users.add(user);
        if (user != null) {
            for (int i = 1; i < 10; i++) { //7*10大概1分钟
                User new_user = new User();
                new_user.setUid(i);
                new_user.setUsername(user.getUsername());
                new_user.setPassword(user.getPassword());
                new_user.setStudentName(user.getStudentName());
                new_user.setStartTime(user.getStartTime());
                new_user.setThreads(user.getThreads());
                new_user.setRobStrategy(user.getRobStrategy());
                new_user.setRobClasses(user.getRobClasses());
                new_user.setRobCommonClasses(user.getRobCommonClasses());
                new_user.setCommonClassCache(user.getCommonClassCache());
                new_user.setRobClassCache(user.getRobClassCache());
                new_user.setRobEnable(user.getRobEnable());
                users.add(new_user);
            }

        }
        return users;
    }

    public static ArrayList<User> getAllUser() {
        ArrayList<User> users = new ArrayList<>();
        ResultSet rs = MysqlUtil.selectUsers();
        System.out.println(rs.toString());
        try {
            while (rs.next()) {
                User user = initUser(rs);
                if (user.getRobEnable() == 1) {
                    users.add(user);
                    User.userCache.put(user.getUsername(), user);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(users);
        return users;
    }


    public static User initUser(ResultSet rs) {
        User user = new User();
        try {
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setStudentName(rs.getString("studentName"));
            user.setStartTime(rs.getString("startTime"));
            user.setThreads(rs.getInt("thread"));
            user.setRobStrategy(RobStrategy.values()[rs.getInt("strategy")]);
            user.setRobClasses((HashSet<String>) JSON.parseObject(rs.getString("robClasses"), HashSet.class));
            HashSet<String> robCommonClasses = (HashSet<String>) JSON.parseObject(rs.getString("robCommonClasses"), HashSet.class);
            if (robCommonClasses == null) {
                robCommonClasses = new HashSet<>();
            }
            user.setRobCommonClasses(robCommonClasses);
            user.setRobEnable(rs.getInt("robEnable"));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }
}


